//
//  SetMyViewController.m
//  何五路
//
//  Created by _ADY on 15/7/28.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "SetMyViewController.h"

@interface SetMyViewController ()

@end

@implementation SetMyViewController
@synthesize allArray,fbDic;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"我的账号";
        self.view.backgroundColor = bgColor;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height) style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    aArray = [NSArray arrayWithObjects:@"头像",@"用户名",@"昵称",@"性别",@"出生日期" ,nil];
    bArray = [NSArray arrayWithObjects:@"地址管理",@"账户安全",nil];
    
    fbDic = [[NSMutableDictionary alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"%@",allArray);
    if (fbDic.count == 0)
    {
        [fbDic setObject:[allArray objectForKey:@"Username"] forKey:@"Username"];
        [fbDic setObject:[allArray objectForKey:@"NickName"] forKey:@"NickName"];
        [fbDic setObject:[allArray objectForKey:@"LxName"] forKey:@"LxName"];
        [fbDic setObject:[allArray objectForKey:@"Phone"] forKey:@"Phone"];
        [fbDic setObject:[allArray objectForKey:@"Email"] forKey:@"Email"];
        [fbDic setObject:[allArray objectForKey:@"Gender"] forKey:@"Gender"];
        [fbDic setObject:[allArray objectForKey:@"DateOfBirthYear"] forKey:@"DateOfBirthYear"];
        [fbDic setObject:[allArray objectForKey:@"DateOfBirthMonth"] forKey:@"DateOfBirthMonth"];
        [fbDic setObject:[allArray objectForKey:@"DateOfBirthDay"] forKey:@"DateOfBirthDay"];
        [fbDic setObject:[allArray objectForKey:@"StateProvinceId"] forKey:@"StateProvinceId"];
        [fbDic setObject:[allArray objectForKey:@"CityId"] forKey:@"CityId"];
        [fbDic setObject:[allArray objectForKey:@"DistrictId"] forKey:@"DistrictId"];
        [fbDic setObject:[allArray objectForKey:@"StreetId"] forKey:@"StreetId"];
        [mTableView reloadData];
        
    }
}

-(void)SetNicknameArray:(NSMutableDictionary*)NicknameArray
{
    fbDic = NicknameArray;
    [mTableView reloadData];
}

#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == 0)
        return 0.001;
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 5;
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0)
        return 80;
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SetMyCell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        aTableView.showsVerticalScrollIndicator = NO;
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"user_unlogin_bg"]];
            imageView1.frame = CGRectMake(screenMySize.size.width - 90,10, 60, 60);
            imageView1.layer.masksToBounds = YES;
            imageView1.layer.cornerRadius = 30;
            [cell.contentView addSubview:imageView1];
        }
        if (indexPath.row == 1)
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",[fbDic objectForKey:@"Username"]];
        }
        if (indexPath.row == 2)
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",[fbDic objectForKey:@"NickName"]];
        }
        if (indexPath.row == 3)
        {
            NSString *xbString = nil;
            if ([[NSString stringWithFormat:@"%@",[fbDic objectForKey:@"Gender"]] isEqualToString:@"M"]) {
                xbString = @"男";
            }
            else if ([[NSString stringWithFormat:@"%@",[fbDic objectForKey:@"Gender"]] isEqualToString:@"F"])
            {
                xbString = @"女";
            }
            else
            {
                xbString = @"保密";
            }
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",xbString];
        }
        if (indexPath.row == 4)
        {
            if (![[NSString stringWithFormat:@"%@",[fbDic objectForKey:@"DateOfBirthYear"]] isEqualToString:@"0"]) {
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@年%@月%@日",[fbDic objectForKey:@"DateOfBirthYear"],[fbDic objectForKey:@"DateOfBirthMonth"],[fbDic objectForKey:@"DateOfBirthDay"]];
            }

        }
        cell.textLabel.text = [aArray objectAtIndex:indexPath.row];
    }
    else
        cell.textLabel.text = [bArray objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)table1View didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            
        }
        else if (indexPath.row == 2)
        {
            SetNicknameViewController *details = [[SetNicknameViewController alloc] init];
            details.delegate =self;
            details.fbDic = fbDic;
            details.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:details animated:YES];
        }
        else if (indexPath.row == 3)
        {
            [self showSheet];
        }
        else if (indexPath.row == 4)
        {
            [self pickerView];
        }
    }
    else
    {
        if (indexPath.row == 0) {
            AddressMangeMentViewController *details = [[AddressMangeMentViewController alloc] init];
            details.hidesBottomBarWhenPushed = YES;
            [details treatedATask];
            [self.navigationController pushViewController:details animated:YES];
        }
        else if (indexPath.row == 1)
        {
            SafetyViewController *details = [[SafetyViewController alloc] init];
            details.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:details animated:YES];
        }
    }
}

-(void)pickerView
{
    if (openpickerButton != nil)
    {
        [openpickerButton removeFromSuperview];
        openpickerButton = nil;
    }
    openpickerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [openpickerButton setFrame:CGRectMake(0, screenMySize.size.height, screenMySize.size.width, screenMySize.size.height)];
    [openpickerButton addTarget:self action:@selector(calcelAction) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:openpickerButton];
    
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, screenMySize.size.height-180-44, screenMySize.size.width, 44)];
    toolBar.tintColor = [UIColor grayColor];
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(sureAction:)];
    UIBarButtonItem* placeHolderButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    placeHolderButton.title = @"请选择时间";
    
    UIBarButtonItem* cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(calcelAction)];
    [toolBar setItems:[NSArray arrayWithObjects:cancelButton, placeHolderButton, doneButton, nil]];
    [openpickerButton addSubview:toolBar];
    
    timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, screenMySize.size.height-180, screenMySize.size.width, 180)];
    timePicker.datePickerMode=UIDatePickerModeDate;
    //    timePicker.datePickerMode = UIDatePickerModeCountDownTimer;//24小时制
    timePicker.backgroundColor = [UIColor grayColor];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date1 = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@-%@-%@",[fbDic objectForKey:@"DateOfBirthYear"],[fbDic objectForKey:@"DateOfBirthMonth"],[fbDic objectForKey:@"DateOfBirthDay"]]];
    if (![[NSString stringWithFormat:@"%@",[fbDic objectForKey:@"DateOfBirthYear"]] isEqualToString:@"0"])
        timePicker.date=date1;
    
    NSLocale* local = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [timePicker setLocale:local];
    [timePicker addTarget:self action:@selector(changes:)forControlEvents:UIControlEventValueChanged];
    [openpickerButton addSubview:timePicker];
    
    
    [UIView animateWithDuration:0.3 animations:^{
        openpickerButton.frame = CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height);
    }];
}

-(void)changes:(id)sender
{
//    [self setTime];
}

-(void)calcelAction
{
    [UIView animateWithDuration:0.5 animations:^{
        openpickerButton.frame = CGRectMake(0, screenMySize.size.height, screenMySize.size.width, screenMySize.size.height);
    }];
    [self performSelector:@selector(afterClose) withObject:self afterDelay:0.5];
}

-(void)afterClose
{
    if (openpickerButton != nil)
    {
        [openpickerButton removeFromSuperview];
        openpickerButton = nil;
    }
}

-(void)sureAction:(id)sender
{
    [self setTime];
    [self calcelAction];
}

-(void)setTime
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dayString = [dateFormatter stringFromDate:[timePicker date]];
    
    [fbDic setObject:[dayString substringWithRange:NSMakeRange(0,4)] forKey:@"DateOfBirthYear"];
    [fbDic setObject:[dayString substringWithRange:NSMakeRange(5,2)] forKey:@"DateOfBirthMonth"];
    [fbDic setObject:[dayString substringWithRange:NSMakeRange(8,2)] forKey:@"DateOfBirthDay"];
    

    
    [self gotoActi];
    
}

-(void)showSheet
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择性别" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男", @"女", @"保密", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.view];
}
#pragma mark - uiactionsheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSArray *array1 = [NSArray arrayWithObjects:@"M", @"F", @"保密", nil];
    if (buttonIndex >= array1.count)
    {

    }
    else
    {
        [fbDic setObject:[array1 objectAtIndex:buttonIndex] forKey:@"Gender"];
        [self gotoActi];
    }
}

-(void)gotoActi
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService SaveInfo:fbDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                NSLog(@"ret %@",ret);
                
                [SendService alerViewMessage:[ret objectForKey:@"Message"]];
                
                if ([[ret objectForKey:@"Result"] isEqualToString:@"success"])
                {
                    [mTableView reloadData];
                }
            }
            
        });
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
